package com.vi.hcnetsdk.simpleapp;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.util.Log;
import android.widget.Toast;
import android.content.Context;
import android.view.inputmethod.InputMethodManager;

/**
 * A login screen that offers login via ip/password.
 */
public class LoginActivity extends AppCompatActivity {
    public final static String DEMOTAG = "SimpleDemo";
    private long firstTime = 0;

    /**
     * A dummy authentication store containing known user names and passwords.
     * TODO: remove after connecting to a real authentication system.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[]{
            "10.17.132.43:8000:hik12345", "10.17.133.46:8000:hik12345"
    };

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;
    private boolean mbSatrt = false;
    // UI references.
    private EditText mIpView;
    private EditText mPasswordView;
    private EditText mUserNameView;
    private EditText mPortView;
    private View mProgressView;
    private View mLoginFormView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.i(DEMOTAG, "Login activity onCreate");

        CrashUtil crashUtil = CrashUtil.getInstance();
        crashUtil.init(this);
        DeviceManage deviceManage = DeviceManage.getInstance();
        if (!deviceManage.init(this)) {
            Log.e(DEMOTAG, "deviceManage init failed");
            this.finish();
            return;
        }

        //set view context
        setContentView(R.layout.activity_login);
        if (!initActivity()) {
            Log.e(DEMOTAG, "initActivity init failed");
            this.finish();
            return;
        }

        //set default view
        mIpView.setText("192.168.12.110");
        mPortView.setText("8000");
        mUserNameView.setText("admin");
        mPasswordView.setText("AbSIMON1");
    }

    // UI references init
    private boolean initActivity() {
        // Set up the login form.
        mIpView = (EditText) findViewById(R.id.IP);
        mPortView = (EditText) findViewById(R.id.port);
        mUserNameView = (EditText) findViewById(R.id.User);

        mPasswordView = (EditText) findViewById(R.id.password);

        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    return signInHandler();
                }
                return false;
            }
        });


        Button mSignInButton = (Button) findViewById(R.id.action_sign_in);
        mSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                signInHandler();
            }
        });

        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);

        return true;
    }

    public void StartMain() {
        Intent intent = new Intent(this, MainActivity.class);
        //String message = editText.getText().toString();
        //intent.putExtra(EXTRA_MESSAGE, message);

        //Intent intent = getIntent();
        //String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
        startActivity(intent);
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        showProgress(false);
        long secondTime = System.currentTimeMillis();
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (secondTime - firstTime < 2000) {
                this.finish();
            } else {
                Toast.makeText(getApplicationContext(), "again exit", Toast.LENGTH_SHORT).show();
                firstTime = System.currentTimeMillis();
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    private boolean signInHandler()
    {
        attemptLogin();
        if(mbSatrt) {
            Log.i(DEMOTAG,"Start main ");
            //StartMain();
        }
        return true;
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }

        // Reset errors.
        mIpView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        String ip = mIpView.getText().toString();
        String password = mPasswordView.getText().toString();
        int nPort = Integer.parseInt(mPortView.getText().toString());
        String userName = mUserNameView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (TextUtils.isEmpty(password) && !isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(ip)) {
            mIpView.setError(getString(R.string.error_field_required));
            focusView = mIpView;
            cancel = true;
        } else if (!isIPValid(ip)) {
            mIpView.setError(getString(R.string.error_invalid_ip));
            focusView = mIpView;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            try {
                ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
                        .hideSoftInputFromWindow(LoginActivity.this
                                        .getCurrentFocus().getWindowToken(),
                                InputMethodManager.HIDE_NOT_ALWAYS);
            } catch (Exception err) {
                Log.e(DEMOTAG, "error: " + err.toString());
            }

            showProgress(true);
            mbSatrt = true;
            mAuthTask = new UserLoginTask(ip, password, nPort, userName);
            mAuthTask.execute((Void) null);
        }
    }
    private boolean isIPValid(String ip) {
        boolean bRet = false;
        int len = 0;
        if(ip.contains(".")) {
            String[] pieces = ip.split("\\.");
            len = pieces.length;
            Log.i(DEMOTAG,"IP:" + ip + " len: " + len);
            if(len == 4) {
                bRet = true;
            }
            while(len-- != 0) {
                if (pieces[len].length() > 3) {
                    bRet = false;
                }
            }
        }
        else
        {
            bRet = false;
        }
        return bRet;
    }

    private boolean isPasswordValid(String password) {
        return password.length() > 4;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mIp;
        private final String mPassword;
        private final String mUserName;
        private int mPort;

        UserLoginTask(String ip, String password, int port, String userName) {
            mIp = ip;
            mPassword = password;
            mUserName = userName;
            mPort = port;
        }
        @Override
        protected void onPreExecute() {
            Log.i(DEMOTAG, "start login device");
        }

        @Override
        protected Boolean doInBackground(Void... params) {

            int iRet = DeviceManage.getInstance().loginNormalDevice(mIp,mPort,mUserName,mPassword);
            // login device failed
            if(iRet < 0)
            {
                Log.e(DEMOTAG, "login device failed,IP: " + mIp);
                return false;
            }

            return true;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            if (success) {
                StartMain();
                //finish();
            } else {

                showProgress(false);
                Toast toast = Toast.makeText(getApplicationContext(),"login failed", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 50, 100);
                toast.show();
                //mPasswordView.setError(getString(R.string.error_incorrect_password));
                mPasswordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }

    @Override
    protected void onRestart()
    {
        Log.i(DEMOTAG, "Login activity onRestart");
        super.onRestart();
        showProgress(false);
        //StartMain();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //super.onSaveInstanceState(outState);
        Log.i(DEMOTAG, "LoginActivity onSaveInstanceState");
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        Log.i(DEMOTAG, "LoginActivity onRestoreInstanceState");
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onStart() {
        Log.i(DEMOTAG, "LoginActivity onStart");
        super.onStart();
    }
    @Override
    protected void onResume() {
        Log.i(DEMOTAG, "LoginActivity onResume");
        super.onResume();
    }
    @Override
    protected void onPause() {
        Log.i(DEMOTAG, "LoginActivity onPause");
        super.onPause();
    }
    @Override
    protected void onStop() {
        Log.i(DEMOTAG, "LoginActivity onStop");
        super.onStop();
    }
    @Override
    protected void onDestroy() {
        Log.i(DEMOTAG, "LoginActivity onDestroy");
        super.onDestroy();
        DeviceManage.getInstance().finalize();
    }
}

